package com.fearless.test03;
/*

       使用JUC完成生产者消费者问题

 */


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {

    static Data2 data2=new Data2();

    public static void main(String[] args) {
        new Thread(()->{

            data2.produce();
        },"生产者").start();


        new Thread(()->{

            data2.consume();
        },"消费者").start();

    }

}

//共享资源类
class Data2{

    Lock lock=new ReentrantLock(true);
    Condition condition = lock.newCondition();

    private int count=0;


        void consume(){

          lock.lock();

          try {
              while (count>0){
                  condition.signalAll();
                  System.out.println("当前库存有"+count+","+Thread.currentThread().getName()+"进行消费");
                  count--;

              }

              condition.await();

          }catch (Exception e){
              e.printStackTrace();
          }finally {
              lock.unlock();
          }

        }


     void produce(){

         lock.lock();


         try {
             while (count==0){
                 condition.signalAll();
                 System.out.println("当前库存是"+count+","+Thread.currentThread().getName()+"进行生产");
                 count++;

             }

             condition.await();

         }catch (Exception e){
             e.printStackTrace();
         }finally {
             lock.unlock();
         }

     }



}